//
//  XJCtySecondViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/6/9.
//  Copyright © 2018年 Tzyang. All rights reserved.
//  分类二级页面
// 参考url http://xinjiangapi.zertone1.com/api/v1/goods/category_goods_list?lat=30.194713&lng=120.189364&page=1&page_size=10&category_id=8
// clv展示 + （上拉刷新、下拉加载） +  点击跳转商品详情页面。


#import "XJCtySecondViewController.h"
#import "RBGoodsDetailViewController.h" // 6-11

//Model
#import "XJCtySecondPageModel.h"
//View
#import "XJCtySecondPageClvItem.h"
#import "RBRefreshFooter.h"
#import "RBRefreshHeader.h"



@interface XJCtySecondViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property(nonatomic, strong) UICollectionView *clv;
/**上拉加载更多 page*/
@property (nonatomic, assign) NSInteger page;

@end

@implementation XJCtySecondViewController
#pragma mark - 一 lazy
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (UICollectionView *)clv {
    if (!_clv) {
        UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
        
        _clv = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight - XJTopNavH-20) collectionViewLayout:flowlayout];
        _clv.backgroundColor = [UIColor whiteColor];
        _clv.delegate = self;
        _clv.dataSource = self;
        
        [_clv registerClass:[XJCtySecondPageClvItem class] forCellWithReuseIdentifier:@"XJCtySecondPageClvItem"];
    }
    
    return _clv;
}


#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 不写有bug
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent  = NO;
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];

    
    [self requestData];
    
    [self.view addSubview:self.clv];
    
    [self setupRefresh];
    
    
}

- (void)setupRefresh {
    // 下拉刷新
    RBRefreshHeader *mj_header = [RBRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    self.clv.mj_header = mj_header;
    [self.clv.mj_header beginRefreshing];
    
    
    // 上拉加载更多
    RBRefreshFooter *mj_footer = [RBRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMoreTopics)];
    self.clv.mj_footer = mj_footer;
    
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    XJCtySecondPageClvItem *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"XJCtySecondPageClvItem" forIndexPath:indexPath];
    
    XJCtySecondPageModel *model = self.dataArray[indexPath.row];
    
    [item configureCtySecondPageClvItemWithIcon:model.cover name:model.name price:model.price marketPrice:model.market_price];
    return item;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    XJCtySecondPageModel *model =    self.dataArray[indexPath.row];
    XJLog(@"%@",model.goodsId);
    
    RBGoodsDetailViewController *goodsDetailVC = [[RBGoodsDetailViewController alloc] init];
    goodsDetailVC.goodsId = model.goodsId;
    [self.navigationController pushViewController:goodsDetailVC animated:YES];
}


#pragma mark -  UICollectionViewDelegateFlowLayout
//UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((KWidth - 10)/ 2, 260);
}


#pragma mark - 请求数据
- (void)requestData {
    
    
    NSDictionary *parDic = @{@"lat":@"30.194713",
                             @"lng":@"120.189364",
                             @"page":@"1",
                             @"page_size":@"20",
                             @"category_id":self.category_id
                             };
    
    self.page = 1;
    [self.clv.mj_header endRefreshing];

    if (self.dataArray.count) {
        [self.dataArray removeAllObjects];
    }
    
    [XJHttpTool requestCategorySecondPageDataWithDic:parDic successH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            NSArray *tempArr = responseObjc[@"data"][@"category_goods_list"];
            for (NSDictionary *dic in tempArr) {
                XJCtySecondPageModel *model = [XJCtySecondPageModel mj_objectWithKeyValues:dic];
                [self.dataArray addObject:model];
            }
            
            // 主线程刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.clv reloadData];
            });
        }
        
        [self.clv.mj_header endRefreshing];
    } failH:^(NSError *error) {
        XJLog(@"失败:%@",error);
        [self.clv.mj_header endRefreshing];
    }];
}

- (void)reloadMoreTopics {
    XJLog(@"来飞机的粉底粉底");
    
    self.page++;
    NSDictionary *parDic = @{@"lat":@"30.194713",
                             @"lng":@"120.189364",
                             @"page":[NSString stringWithFormat:@"%ld",self.page],
                             @"page_size":@"20",
                             @"category_id":self.category_id
                             };
    
    [self.clv.mj_header endRefreshing];
    
    [XJHttpTool requestCategorySecondPageDataWithDic:parDic successH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            NSArray *tempArr = responseObjc[@"data"][@"category_goods_list"];
            
            if (tempArr.count) {
                for (NSDictionary *dic in tempArr) {
                    XJCtySecondPageModel *model = [XJCtySecondPageModel mj_objectWithKeyValues:dic];
                    [self.dataArray addObject:model];
                }
                
                // 主线程刷新
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.clv reloadData];
                });
            }
        }
        
        [self.clv.mj_footer endRefreshingWithNoMoreData];
    } failH:^(NSError *error) {
        XJLog(@"失败:%@",error);
        [self.clv.mj_footer endRefreshingWithNoMoreData];
    }];
}


@end
